package com.example.abe.diandi.user.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

import com.example.BindView;
import com.example.abe.diandi.R;
import com.example.abe.diandi.base.BaseActivity;
import com.example.abe.diandi.home.activity.HomeActivity;
import com.example.abe.diandi.main.AppConfig;
import com.example.abe.diandi.nohttp.ApiUtil;
import com.example.abe.diandi.nohttp.CallServer;
import com.example.abe.diandi.nohttp.HttpListener;
import com.example.abe.diandi.user.model.UserModel;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

import example.abe.com.framework.util.SharedPreferencesUtil;

import static com.example.abe.diandi.nohttp.ApiUtil.METHOD;
import static com.example.abe.diandi.nohttp.ApiUtil.M_USER_LOGIN;
import static com.example.abe.diandi.nohttp.ApiUtil.SERVICE;
import static com.example.abe.diandi.nohttp.ApiUtil.S_USER;

public class WelcomeActivity extends BaseActivity {

    private static long ANIM_SCALE_DURATION = 1000;

    @BindView(R.id.act_welcome_iv)
    protected ImageView mIv;

    private String mStrUsername;
    private String mStrPassword;
    private long mTempTimeStamp;

    @Override
    public int getLayoutID() {
        return R.layout.activity_welcome;
    }

    @Override
    public void initData() {
        mStrPassword = SharedPreferencesUtil.get(AppConfig.PASSWORD, "");
        mStrUsername = SharedPreferencesUtil.get(AppConfig.NAME, "");
        mTempTimeStamp = System.currentTimeMillis();
    }

    @Override
    public void initView() {
        //隐藏状态栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //设置图片
        mIv.setImageResource(R.drawable.bg_welcome);
        Animation scaleAnimation = AnimationUtils.loadAnimation(this, R.anim.welcome_view_blow_up);
        scaleAnimation.setFillAfter(true);
        mIv.setAnimation(scaleAnimation);
        //自动登陆操作
        autoLoginNetworkRequest();
    }

    private void autoLoginNetworkRequest(){
        if (!TextUtils.isEmpty(mStrUsername) && !TextUtils.isEmpty(mStrPassword)) {
            Request<String> request = NoHttp.createStringRequest(ApiUtil.URL, RequestMethod.POST);
            request.add(SERVICE, S_USER)
                    .add(METHOD, M_USER_LOGIN)
                    .add("name", mStrUsername)
                    .add("password", mStrPassword);
            CallServer.getInstance().add(this, false, request, new HttpListener<String>() {

                @Override
                public void onSucceed(int what, Response<String> response) {
                    JsonObject jsonObj = new JsonParser().parse(response.get()).getAsJsonObject();
                    Boolean isSuccess = jsonObj.get("success").getAsBoolean();
                    if (isSuccess) {
                        JsonObject data = jsonObj.getAsJsonObject("data");
                        UserModel model = new Gson().fromJson(data, UserModel.class);
                        AppConfig.clear();
                        AppConfig.setCategoryList(model.getListCategory());
                        AppConfig.setUserModel(model);
                        SharedPreferencesUtil.put(AppConfig.NAME, model.getName());
                        SharedPreferencesUtil.put(AppConfig.PASSWORD, model.getPassword());
                    }
                    doAutoLogin(isSuccess);
                }

                @Override
                public void onFailed(int what, Response<String> response) {
                    doAutoLogin(false);
                }
            });
        }else {
            doAutoLogin(false);
        }
    }

    /**
     * 自动登陆操作
     * @param isSuccess 登陆是否成功
     */
    private void doAutoLogin(boolean isSuccess){
        //为了更好的用户体验，登陆操作需要等到动画执行完毕才进行
        long curTimeStamp = System.currentTimeMillis();
        if (isSuccess){
            if (curTimeStamp - mTempTimeStamp > ANIM_SCALE_DURATION){
                Intent intent = new Intent(WelcomeActivity.this, HomeActivity.class);
                startActivity(intent);
                finish();
            }else {
                uiHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(WelcomeActivity.this, HomeActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }, ANIM_SCALE_DURATION - (curTimeStamp - mTempTimeStamp));
            }
        }else {
            if (curTimeStamp - mTempTimeStamp > ANIM_SCALE_DURATION){
                Intent intent = new Intent(WelcomeActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
            }else {
                uiHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(WelcomeActivity.this, LoginActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }, ANIM_SCALE_DURATION - (curTimeStamp - mTempTimeStamp));
            }
        }
    }
}
